﻿using Newtonsoft.Json;
using NoticeHelper.Dingtalk.Messages;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace NoticeHelper.Dingtalk.DingtalkCustomRobotSdk
{
    /// <summary>
    /// https://developers.dingtalk.com/document/app/custom-robot-access
    /// </summary>
    public class DingtalkClient
    {
        public static DingtalkClient Instance { get; private set; }
        private static HttpClient _httpClient = new HttpClient(new HttpClientHandler
        {
            AutomaticDecompression = System.Net.DecompressionMethods.All,
        });
        private DingtalkOptions _dingtalkCustomRobotOptions;

        public DingtalkClient(DingtalkOptions dingtalkCustomRobotOptions)
        {
            _dingtalkCustomRobotOptions = dingtalkCustomRobotOptions;
        }

        public static void Init(string urlBase, string secret = default)
        {
            Instance = new DingtalkClient(new DingtalkOptions
            {
                UrlBase = urlBase,
                Secret = secret
            });
        }

        public Task<DingtalkResponse> SendTextAsync(string text) => SendTextAsync(new TextMessage(text));
        public Task<DingtalkResponse> SendTextAsync(TextMessage message) => SendAsync(message);

        public Task<DingtalkResponse> SendMarkdownAsync(string title, string text) => SendMarkdownAsync(new MarkdownMessage(title, text ?? title));
        public Task<DingtalkResponse> SendMarkdownAsync(MarkdownMessage message) => SendAsync(message);

        public Task<DingtalkResponse> SendActionCardAsync(string title, string text, string singleTitle, string singleURL, string btnOrientation = "0") => SendActionCardAsync(new ActionCardMessage(title, text, singleTitle, singleURL, btnOrientation));
        public Task<DingtalkResponse> SendActionCardAsync(ActionCardMessage message) => SendAsync(message);

        private async Task<DingtalkResponse> SendAsync(MessageBase message)
        {
            var response = await _httpClient.PostAsync(_dingtalkCustomRobotOptions.RequestUrl, new StringContent(message.ToString(), Encoding.UTF8, "application/json")).ConfigureAwait(false);
            var html = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            return JsonConvert.DeserializeObject<DingtalkResponse>(html);
        }
    }
}
